import { Ball } from "./_ball";

//玩家
export class Player {
  x = 100;
  y = 350;
  width = 300;
  height = 50;
  speed = 10;

  constructor(private canvasWidth: number, private canvasHeight: number) {}
  moveLeft() {
    let nextX = this.x - this.speed;
    if (nextX < 0) nextX = 0;
    this.x = nextX;
  }

  moveRight() {
    let nextX = this.x + this.speed;
    if (nextX > this.canvasWidth - this.width)
      nextX = this.canvasWidth - this.width;
    this.x = nextX;
  }

  moveTop() {
    let nextY = this.y - this.speed;
    if (nextY < 0) nextY = 0;
    this.y = nextY;
  }

  moveBottom() {
    let nextY = this.y + this.speed;
    if (nextY > this.canvasHeight - this.height)
      nextY = this.canvasHeight - this.height;
    this.y = nextY;
  }

  //检测相撞
  collide(b: Ball) {
    //两个矩形中心点 x轴距离 <= 两个矩形宽和的一半 &&
    //两个矩形中心点 y轴距离 <= 两个矩形高和的一半
    const a = this;
    const cond1 = [a.x + a.width / 2, a.y + a.height / 2];
    const cond2 = [b.x + b.width / 2, b.y + b.height / 2];
    const cx = Math.abs(cond1[0] - cond2[0]);
    const cy = Math.abs(cond1[1] - cond2[1]);
    if (cx <= (a.width + b.width) / 2 && cy <= (a.height + b.height) / 2) {
      return true;
    }
    return false;
  }
}
